package com.runachina.common;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.runachina.R;
import com.runachina.runa.ReadMeterActivity;
import com.runachina.util.Base64Util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;


/**
 * Created by lyl on 2017/8/1.
 */

public class NewLoginActivity extends BaseActivity {
    private static final String TAG = "lyl";
    private Button btnlogin;
    private EditText registercode, registertime, duetime;
    private TextView macAdd;
    private int madom_shou, madom_mo;
    private String expireData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_new);
        set_toolbar("注册", "");
        init_view();

        //每次进来都判断是否到期
        if (readLocalCfg("endTimeCfg") != null && !TextUtils.isEmpty(readLocalCfg("endTimeCfg"))) {
            Log.e(TAG, "onCreate: " + readLocalCfg("endTimeCfg"));
            if (getTimeLeft(readLocalCfg("endTimeCfg")) > 0 && judgeTimeMode() == 1) {
                startActivity(new Intent(NewLoginActivity.this, ReadMeterActivity.class));
                finish();//没有到期
            }
        }
    }

    private void init_view() {
        btnlogin = (Button) findViewById(R.id.btnlogin);
        btnlogin.setOnClickListener(loginFun);
        macAdd = (TextView) findViewById(R.id.mac);
        registercode = (EditText) findViewById(R.id.registercode);
        registertime = (EditText) findViewById(R.id.registertime);
        duetime = (EditText) findViewById(R.id.duetime);
        madom_shou = getMathRadom();//首位验证码
        madom_mo = getMathRadom();//末尾验证码
        macAdd.setText("首位验证码:" + madom_shou + "   末位验证码:" + madom_mo);

        registercode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().trim().length() == 24) {
                    duetime.setText("到期时间：" + getExpireData());
                } else {
                    duetime.setText("到期时间：");
                }
            }
        });
    }

    private View.OnClickListener loginFun = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (TextUtils.isEmpty(registercode.getText().toString())) {
                show("请输入注册码");
                return;
            }
            //判断注册码是否正确
            checkRegisterCode();
        }
    };

    //判断注册码是否正确
    private void checkRegisterCode() {
        String registerCode = registercode.getText().toString();
        if (registerCode.length() == 24) {
            registerCode = Base64Util.decode(registerCode);
            if (registerCode.length() > 6) {
                //获取首位验证码
                String madom_shou1 = registerCode.substring(0, 3);
                //获取末尾验证码
                String madom_mo1 = registerCode.substring(3, 6);
                if (!isDigit(madom_shou1)) {
                    show("注册码错误");
                    return ;
                }
                if (!isDigit(madom_mo1)) {
                    show("注册码错误");
                    return ;
                }
                //验证验证码是否正确
                if (Integer.parseInt(madom_shou1) - 134 == madom_shou && Integer.parseInt(madom_mo1) - 147 == madom_mo) {
                    //跳转
                    Log.e(TAG, "注册成功");
                    Log.e(TAG, "madom_shou: " + madom_shou);
                    Log.e(TAG, "madom_mo: " + madom_mo);
                    //获取到期时间
                    expireData = Base64Util.decode(registerCode.substring(6, registerCode.length()));
                    //到期时间
                    //dateToStamp(expireData);
                    //当前时间
                    //dateToStamp(new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime()));
                    if (getTimeLeft(expireData) > 0) {
                        //获取到期时间-保存
                        writeLocalCfg("endTimeCfg", expireData);
                        //跳转
                        startActivity(new Intent(NewLoginActivity.this, ReadMeterActivity.class));//读取抄表
                        finish();
                        Log.e(TAG, "checkRegisterCode: 未到期");
                    } else {
                        Log.e(TAG, "checkRegisterCode: 到期");
                    }

                } else {
                    show("注册码错误");
                    return;
                }
            }
        } else {
            show("注册码错误");
            return;
        }
        Log.e(TAG, "checkRegisterCode: " + registerCode);
    }

    //获取0到800以内的随机码
    public int getMathRadom() {
        Random rand = new Random();
        int i = rand.nextInt(); //int范围类的随机数
        // i = rand.nextInt(100); //生成0-100以内的随机数
        i = (int) (Math.random() * 800); //0-100以内的随机数，用Matn.random()方式
        return i;
    }

    /*
  * 将时间转换为时间戳
  */
    public static long dateToStamp(String s) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ts = date.getTime();
        return ts;
    }

    int judgeTimeMode() {
        int mode = 0;//自动时间就是1，手动时间就是0
        try {
            mode = android.provider.Settings.System.getInt(getContentResolver(), android.provider.Settings.System.AUTO_TIME);
        } catch (Exception e) {
        }
        ;
        return mode;
    }

    //获取剩余时间
    public long getTimeLeft(String expireData) {
        long time;
        time = dateToStamp(expireData) - dateToStamp(new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime()));
        return time;
    }

    ///获取到期时间
    public String getExpireData() {
        String registerCode = registercode.getText().toString();
        registerCode = Base64Util.decode(registerCode);
        if (registerCode.length() > 6) {
            //获取首位验证码
            String madom_shou1 = registerCode.substring(0, 3);
            //获取末尾验证码
            String madom_mo1 = registerCode.substring(3, 6);
            if (!isDigit(madom_shou1)) {
                return "";
            }
            if (!isDigit(madom_mo1)) {
                return "";
            }
            //验证验证码是否正确
            if (Integer.parseInt(madom_shou1) - 134 == madom_shou && Integer.parseInt(madom_mo1) - 147 == madom_mo) {
                //获取到期时间
                expireData = Base64Util.decode(registerCode.substring(6, registerCode.length()));
                return expireData;
            } else {
                //  show("注册码错误");
                return "";
            }
        }
        return "";
    }


    // 判断一个字符串是否都为数字
    public boolean isDigit(String strNum) {
        return strNum.matches("[0-9]{1,}");
    }
}
